<template>
  <page>
    <el-row style="height:100%" class="an-goods-type">
      <el-col :span="8" class="an-tree">
        <h3>全部分类</h3>
        <el-tree :data="treeData" :props="defaultProps" default-expand-all v-loading="loading"></el-tree>
      </el-col>
      <el-col :span="8" class="an-main-type">
        <type-list :title="'主类'" :list="firstType" @call-back="clickFirstType" />
      </el-col>
      <el-col :span="8">
        <type-list
          :title="'二级分类'"
          :list="secondType"
          :parentID="tageParentID"
          @call-back="clickFirstType"
        />
      </el-col>
    </el-row>
  </page>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import { GoodsType } from "@/utils/interface";
import page from "@/components/Page/index.vue";
import typeList from "./typeList/index.vue";
import { useStore } from "vuex";

interface GoodsTree extends GoodsType {
  children: Array<GoodsType>;
}
@Options({
  components: {
    page,
    typeList,
  },
  computed: {
    list() {
      return this.store.state.appModule.goodsType;
    },
  },
  watch: {
    list: {
      handler(nd) {
        let arry = JSON.parse(JSON.stringify(nd));
        this.updataType(arry);
      },
      immediate: true,
    },
  },
})
export default class goodsType extends Vue {
  [x: string]: any;
  store = useStore();
  treeData: Array<GoodsType> = [];
  firstType: Array<GoodsType> = [];
  secondType: Array<GoodsType> = [];
  defaultProps = {
    children: "children",
    label: "typeName",
  };
  loading: Boolean = false;
  tageParentID: Number = 0;

  created() {
    this.getList();
  }
  // 获取分类数据
  getList() {
    this.loading = true;
    this.$store.dispatch("appModule/getGoodsType").then(() => {
      this.loading = false;
    });
  }

  // 更新数据
  updataType(res: Array<GoodsType>) {
    let nd: Array<GoodsTree> = [];
    res.forEach((item) => {
      if (!item.parentID) {
        let newObj = Object.assign(item);
        newObj.children = [];
        nd.push(newObj);
      }
    });
    this.firstType = nd;
    this.treeData = this.AUTH.createTree([...res], "id", "parentID");
  }

  // 主分类选中
  clickFirstType(obj: GoodsType) {
    if (!obj.parentID) {
      this.tageParentID = obj.id;
      let nd: Array<GoodsType> = [];
      this.list.forEach((item: GoodsType) => {
        if (item.parentID == obj.id) {
          nd.push(item);
        }
      });
      this.secondType = nd;
    }
  }
}
</script>

<style lang="scss">
@import "../../style/mixin.scss";
.an-goods-type {
  .an-tree {
    padding: 0 15px;
    background-color: $color-border4;
    .el-tree {
      background: transparent;
    }
  }
  .an-main-type {
    padding: 0 15px;
  }
}
</style>